package cn.mrlong.recordandplay;

import android.media.MediaRecorder;
import android.os.Handler;
import android.os.Message;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 录制类
 */
public class RecordUtil {
    private static int MESSAGE_RECORD = 99991;
    private MediaRecorder mediaRecorder;
    public boolean isRecording = false;
    private RecordTimeCallback callback;
    // 相关变量
    private int second = 0;
    private int minute = 0;
    private int hour = 0;
    private Timer timer;
    // 计时器异步更新界面
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (MESSAGE_RECORD == msg.what)
                callback.recordTime(getFormatTime());
        }
    };

    private String getFormatTime() {
        return String.format("%1$02d:%2$02d:%3$02d", hour, minute, second);
    }

    private long limitTime = 0;// 录音文件最短事件1秒

    public interface RecordTimeCallback {
        abstract void recordTime(String time);

        abstract void noticeMsg(String msg);

        abstract void recordSucc(String file, String fileRecordTime);
    }


    public RecordUtil(RecordTimeCallback callback) {
        this.callback = callback;
    }

    private String outFilePath = "";

    /**
     * 开始录制
     */
    public void startRecord(String outFilePath) {
        this.outFilePath = outFilePath;
        if (mediaRecorder == null) {
            mediaRecorder = new MediaRecorder();
        } else {
            mediaRecorder.reset();
        }
        /**
         * mediaRecorder.setAudioSource设置声音来源。
         * MediaRecorder.AudioSource这个内部类详细的介绍了声音来源。
         * 该类中有许多音频来源，不过最主要使用的还是手机上的麦克风，MediaRecorder.AudioSource.MIC
         */
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        /**
         * mediaRecorder.setOutputFormat代表输出文件的格式。该语句必须在setAudioSource之后，在prepare之前。
         * OutputFormat内部类，定义了音频输出的格式，主要包含MPEG_4、THREE_GPP、RAW_AMR……等。
         */
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
        /**
         * mediaRecorder.setAddioEncoder()方法可以设置音频的编码
         * AudioEncoder内部类详细定义了两种编码：AudioEncoder.DEFAULT、AudioEncoder.AMR_NB
         */
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        /**
         * 设置录音之后，保存音频文件的位置,一般是SD卡的位置
         */
        mediaRecorder.setOutputFile(outFilePath);

        /**
         * 调用start开始录音之前，一定要调用prepare方法。
         */
        try {
            mediaRecorder.prepare();
            mediaRecorder.start();
            limitTime = System.currentTimeMillis();
            // 录音计时
            recordTime();
            isRecording = true;
        } catch (Exception e) {
            isRecording = false;
            resetTimeParams();
            e.printStackTrace();
        }
    }


    /**
     * 记录录音时间
     */
    private void recordTime() {
        if (timer != null) {
            timer.cancel();
        }
        TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                second++;
                if (second >= 60) {
                    second = 0;
                    minute++;
                    if (minute >= 60) {
                        minute = 0;
                        hour++;
                    }
                }
                handler.sendEmptyMessage(MESSAGE_RECORD);
            }

        };
        timer = new Timer();
        timer.schedule(timerTask, 1000, 1000);
    }

//    /**
//     * 暂停录音
//     * api 24 支持
//     */
//    @RequiresApi(api = Build.VERSION_CODES.N)
//    public void pauseRecord() {
//        if (null != mediaRecorder && isRecording) {
//            mediaRecorder.pause();
//            isRecording = false;
//        }
//
//    }

//    /**
//     * 恢复录制
//     * api 24 支持
//     */
//    @RequiresApi(api = Build.VERSION_CODES.N)
//    public void resumeRecord() {
//        if (null != mediaRecorder && !isRecording) {
//            mediaRecorder.resume();
//            isRecording = true;
//        }
//    }

    /**
     * 重置录音
     */
    public void resetRecord() {
        if (null != mediaRecorder) {
            mediaRecorder.reset();
            resetTimeParams();
            isRecording = false;
        }
    }

    /**
     * 释放
     */
    public void stopRecord() {
        if (System.currentTimeMillis() - limitTime < 1100) {
            //录音文件不得低于一秒钟
            callback.noticeMsg("录音时间长度不得低于1秒钟！");
            return;
        }

        if (null != mediaRecorder) {
            mediaRecorder.stop();
            mediaRecorder.release();
            callback.recordSucc(outFilePath, getFormatTime());
            resetTimeParams();
            mediaRecorder = null;
        }
        if (null != timer) {
            timer.cancel();
            timer = null;
        }

        isRecording = false;

    }

    public void onDestory() {
        if (null != handler) {
            handler = null;
        }
        if (null != timer) {
            timer.cancel();
            timer = null;
        }
        if (null != mediaRecorder) {
            mediaRecorder.stop();
            mediaRecorder.release();
            mediaRecorder = null;
        }
    }

    /**
     * 重置时间
     */
    private void resetTimeParams() {
        minute = 0;
        hour = 0;
        second = 0;
    }

}

